import json
import tornado
import tornado.websocket
import tornado.web
from db import db
conndict = {}

class WebsockHandler(tornado.websocket.WebSocketHandler):
    # 跨域支持
    def check_origin(self,origin):
        return True
    #建立连接
    def open(self):
        # 获取参数
        id = int(self.get_query_argument('id'))
        # 存储链接
        conndict[id] = self

    def on_message(self,mes):
        print(mes)
    def on_close(self):
        pass

class TTHander(tornado.web.RequestHandler):
    def get(self):
        msg = self.get_query_argument('mes')
        id = int(self.get_query_argument('id'))
        conndict[id].write_message(msg)



class Greenhouse(tornado.web.RequestHandler):
    def get(self):
        id = int(self.get_query_argument('id'))

        sql = "select * from greenhouse"
        res = db.findall(sql)
        print(res)
        list = []
        for i in res:
            if i['min'] <=i['temp']<=i['max']:
                status = 1
                list.append({'id':i['id'],'name':i['name'],'temp':i['temp'],'min':i['min'],'max':i['max'],'status':status})
            else:
                status = 0
                list.append({'id':i['id'],'name':i['name'],'temp':i['temp'],'min':i['min'],'max':i['max'],'status':status})
        print(list)
        conndict[id].write_message(json.dumps(list))

